package com.neusoft.hifly.information.comment.service.impl;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.neusoft.hifly.commons.exception.SystemErrorException;
import com.neusoft.hifly.commons.lang.LongUtil;
import com.neusoft.hifly.commons.lang.StringConstants;
import com.neusoft.hifly.core.basic.service.impl.CTSaaSBaseServiceImpl;
import com.neusoft.hifly.core.log.annotation.LogType;
import com.neusoft.hifly.core.log.annotation.OperationLog;
import com.neusoft.hifly.core.token.TokenContextHolder;
import com.neusoft.hifly.dynamicds.multi.annotation.MultiDynamicRoutingDataSource;
import com.neusoft.hifly.information.comment.dao.IArticleCommentDao;
import com.neusoft.hifly.information.comment.entity.ArticleCommentObj;
import com.neusoft.hifly.information.comment.service.IArticleCommentService;

/**
 * Title: 文章资讯服务
 * <p>
 * Description: 文章评论 Service
 * <p>
 * Copyright: 2019
 * <p>
 * Company: 东软汉枫
 *
 * @author lh_neu
 * @version 1.0.0
 */
@Service
@MultiDynamicRoutingDataSource
public class ArticleCommentServiceImpl extends CTSaaSBaseServiceImpl implements IArticleCommentService {
	@Autowired(required = false)
	private IArticleCommentDao articleCommentDao;

	/**
	 * 保存对象
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param obj
	 *            对象
	 * @throws SystemErrorException
	 *             自定义异常
	 */
	@Override
	@OperationLog(method = LogType.UPDATE, msg = "文章评论")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class, RuntimeException.class })
	public void saveOrUpdate(final String organCode, final long organLogicId, final ArticleCommentObj obj)
			throws SystemErrorException {
		if (StringUtils.isEmpty(organCode) || obj == null) {
			return;
		}
		if (StringUtils.isEmpty(obj.getOrganCode())) {
			obj.setOrganCode(organCode);
		}
		if (LongUtil.isEmpty(obj.getOrganLogicId())) {
			obj.setOrganLogicId(organLogicId);
		}

		final ArticleCommentObj oldObj = articleCommentDao.getByLogicId(organCode, organLogicId, obj.getLogicId());

		obj.setOrganLogicId(organLogicId);

		// 有ID的话要判断是否保存还是更新
		if (oldObj == null) {
			// 保存

			obj.setId(idWorker.nextId());
			if (LongUtil.isEmpty(obj.getLogicId())) {
				obj.setLogicId(idWorker.nextId());
			}
			obj.setContentTime(LocalDateTime.now());

			this.setForm(obj, obj);

			articleCommentDao.insert(obj);

		} else {
			// 更新

			this.setForm(obj, oldObj);

			articleCommentDao.updateById(oldObj);

		}
	}

	/**
	 * 批量审核评论
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param logicIds
	 *            对象ID
	 * @param isApprove
	 *            是否审核通过
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class, RuntimeException.class })
	public void updateIsApproveByBatch(final String organCode, final long organLogicId, final String logicIds,
			final String isApprove) {
		if (StringUtils.isEmpty(organCode) || StringUtils.isEmpty(logicIds) || StringUtils.isEmpty(isApprove)) {
			return;
		}
		final String[] logicIdArr = logicIds.split(StringConstants.STRING_SPLIT_FLAG_3);
		if (logicIdArr == null) {
			return;
		}

		ArticleCommentObj obj = null;
		for (final String logicId : logicIdArr) {
			if (StringUtils.isNotEmpty(logicId)) {
				obj = articleCommentDao.getByLogicId(organCode, organLogicId, Long.parseLong(logicId));
				if (obj == null) {
					continue;
				}
				obj.setApprovePerson(TokenContextHolder.get().getUserName());
				obj.setApproveTime(LocalDateTime.now());
				obj.setIsApprove(isApprove);
				articleCommentDao.updateById(obj);
			}
		}
	}

	/**
	 * 根据ID删除对象
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param logicId
	 *            对象ID
	 */
	@Override
	@OperationLog(method = LogType.DELETE, msg = "文章评论")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class, RuntimeException.class })
	public void deleteByLogicId(final String organCode, final long organLogicId, final long logicId) {
		if (StringUtils.isEmpty(organCode)) {
			return;
		}

		articleCommentDao.deleteByLogicId(organCode, organLogicId, logicId);
	}

	/**
	 * 批量删除对象
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param logicIds
	 *            对象ID，多id使用英文逗号分隔
	 */
	@Override
	public void deleteByBatch(final String organCode, final long organLogicId, final String logicIds) {
		if (StringUtils.isEmpty(organCode) || StringUtils.isEmpty(logicIds)) {
			return;
		}
		final String[] logicIdArr = logicIds.split(StringConstants.STRING_SPLIT_FLAG_3);
		if (logicIdArr == null) {
			return;
		}
		for (final String logicId : logicIdArr) {
			if (StringUtils.isEmpty(logicId)) {
				continue;
			}
			this.deleteByLogicId(organCode, organLogicId, Long.parseLong(logicId));
		}
	}

	/**
	 * 根据id查询对象
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param logicId
	 *            对象logicId
	 * @return 对象
	 */
	@Override
	public ArticleCommentObj getByLogicId(final String organCode, final long organLogicId, final long logicId) {
		if (StringUtils.isEmpty(organCode)) {
			return null;
		}
		return articleCommentDao.getByLogicId(organCode, organLogicId, logicId);
	}

	/**
	 * 查询文章评论
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param articleLogicId
	 *            文章逻辑ID
	 * @return 对象集合
	 */

	@Override
	public List<ArticleCommentObj> findByArticleLogicId(final String organCode, final long organLogicId,
			final long articleLogicId) {
		if (StringUtils.isEmpty(organCode)) {
			return null;
		}

		return articleCommentDao.findByArticleLogicId(organCode, organLogicId, articleLogicId);
	}

	/**
	 * 查询所有对象
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @return 对象集合
	 */
	@Override
	public List<ArticleCommentObj> findAll(final String organCode, final long organLogicId) {
		if (StringUtils.isEmpty(organCode)) {
			return null;
		}
		return articleCommentDao.findAll(organCode, organLogicId);
	}

	/**
	 * 根据条件查询
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param property
	 *            参数。其中isLike:Boolean 是否模糊查询
	 * @return 集合
	 */
	@Override
	public List<ArticleCommentObj> search(final String organCode, final long organLogicId,
			Map<String, Object> property) {
		if (StringUtils.isEmpty(organCode)) {
			return null;
		}
		if (property == null) {
			property = new HashMap<String, Object>(1);
			property.put("organLogicId", organLogicId);
		}
		final QueryWrapper<ArticleCommentObj> queryWrapper = new QueryWrapper<ArticleCommentObj>();
		replaceProperty(property);
		createSql(property, queryWrapper, new String[] { "CONTENT_TIME" });
		return articleCommentDao.selectList(queryWrapper);
	}

	/**
	 * 根据条件查询
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param offset
	 *            当前页数
	 * @param limit
	 *            分页长度
	 * @param property
	 *            参数。其中isLike:Boolean 是否模糊查询
	 * @return 返回Map
	 */
	@Override
	public IPage<ArticleCommentObj> search(final String organCode, final long organLogicId, final int offset,
			final int limit, Map<String, Object> property) {
		if (StringUtils.isEmpty(organCode)) {
			return null;
		}
		if (property == null) {
			property = new HashMap<String, Object>(1);
			property.put("organLogicId", organLogicId);
		}
		final IPage<ArticleCommentObj> page = new Page<ArticleCommentObj>(offset, limit);
		final QueryWrapper<ArticleCommentObj> queryWrapper = new QueryWrapper<ArticleCommentObj>();
		replaceProperty(property);
		createSql(property, queryWrapper, new String[] { "CONTENT_TIME" });
		return articleCommentDao.selectPage(page, queryWrapper);
	}

	/**
	 * 复制信息
	 *
	 * @param fromObj
	 *            原信息
	 * @param toObj
	 *            新信息
	 */
	private void setForm(final ArticleCommentObj fromObj, final ArticleCommentObj toObj) {
		toObj.setOrganLogicId(fromObj.getOrganLogicId());
		toObj.setPid(fromObj.getPid());
		toObj.setArticleLogicId(fromObj.getArticleLogicId());
		toObj.setUserName(StringUtils.trimToEmpty(fromObj.getUserName()));
		toObj.setUserLogicId(fromObj.getUserLogicId());
		toObj.setContent(StringUtils.trimToEmpty(fromObj.getContent()));
		toObj.setContentTime(fromObj.getContentTime());
		toObj.setIsAnonymous(StringUtils.trimToEmpty(fromObj.getIsAnonymous()));
		toObj.setSignature(StringUtils.trimToEmpty(fromObj.getSignature()));
		toObj.setIsApprove(StringUtils.trimToEmpty(fromObj.getIsApprove()));
		toObj.setApprovePerson(StringUtils.trimToEmpty(fromObj.getApprovePerson()));
		toObj.setApproveTime(fromObj.getApproveTime());
		toObj.setExt1(StringUtils.trimToEmpty(fromObj.getExt1()));
		toObj.setExt2(StringUtils.trimToEmpty(fromObj.getExt2()));
		toObj.setExt3(StringUtils.trimToEmpty(fromObj.getExt3()));
		toObj.setExt4(StringUtils.trimToEmpty(fromObj.getExt4()));
		toObj.setExt5(StringUtils.trimToEmpty(fromObj.getExt5()));

	}

	/**
	 * 将对象属性替换成数据库列
	 *
	 * @param property
	 *            参数
	 */
	private void replaceProperty(final Map<String, Object> property) {
		if (property != null) {
			if (property.containsKey("organLogicId")) {
				property.put("ORGAN_LOGIC_ID", property.get("organLogicId"));
				property.remove("organLogicId");
			}
			if (property.containsKey("pid")) {
				property.put("PID", property.get("pid"));
				property.remove("pid");
			}
			if (property.containsKey("articleLogicId")) {
				property.put("ARTICLE_LOGIC_ID", property.get("articleLogicId"));
				property.remove("articleLogicId");
			}
			if (property.containsKey("userName")) {
				property.put("USER_NAME", property.get("userName"));
				property.remove("userName");
			}
			if (property.containsKey("userLogicId")) {
				property.put("USER_LOGIC_ID", property.get("userLogicId"));
				property.remove("userLogicId");
			}
			if (property.containsKey("content")) {
				property.put("CONTENT", property.get("content"));
				property.remove("content");
			}
			if (property.containsKey("contentTime")) {
				property.put("CONTENT_TIME", property.get("contentTime"));
				property.remove("contentTime");
			}
			if (property.containsKey("isAnonymous")) {
				property.put("IS_ANONYMOUS", property.get("isAnonymous"));
				property.remove("isAnonymous");
			}
			if (property.containsKey("signature")) {
				property.put("SIGNATURE", property.get("signature"));
				property.remove("signature");
			}
			if (property.containsKey("isApprove")) {
				property.put("IS_APPROVE", property.get("isApprove"));
				property.remove("isApprove");
			}
			if (property.containsKey("approvePerson")) {
				property.put("APPROVE_PERSON", property.get("approvePerson"));
				property.remove("approvePerson");
			}
			if (property.containsKey("approveTime")) {
				property.put("APPROVE_TIME", property.get("approveTime"));
				property.remove("approveTime");
			}
			if (property.containsKey("ext1")) {
				property.put("EXT1", property.get("ext1"));
				property.remove("ext1");
			}
			if (property.containsKey("ext2")) {
				property.put("EXT2", property.get("ext2"));
				property.remove("ext2");
			}
			if (property.containsKey("ext3")) {
				property.put("EXT3", property.get("ext3"));
				property.remove("ext3");
			}
			if (property.containsKey("ext4")) {
				property.put("EXT4", property.get("ext4"));
				property.remove("ext4");
			}
			if (property.containsKey("ext5")) {
				property.put("EXT5", property.get("ext5"));
				property.remove("ext5");
			}

		}
	}
}